<template>
  <page-layout>
    <a-row :gutter="[10, 10]">
      <a-col :span="24">
        <a-card>
          <footer-button :buttons="formState.buttons" />
          <a-form
            ref="formRef"
            :model="modelFrom.data"
            :rules="formRules"
            :labelCol="{ span: 9 }"
          >
            <a-row>
              <a-col :span="8">
                <a-form-item
                  :label="t('activityManage.label.activityName')"
                  v-bind="validateInfos.actName"
                  name="actName"
                >
                  <a-input
                    v-model:value="modelFrom.data.actName"
                    :maxlength="100"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  :label="t('activityManage.label.ativityStartTime')"
                  v-bind="validateInfos.beginTime"
                  name="beginTime"
                >
                  <a-date-picker
                    style="width: 100%"
                    v-model:value="modelFrom.data.beginTime"
                    :placeholder="t('placeholder.pleaseSelect')"
                    valueFormat="YYYY-MM-DD HH:mm:ss"
                    allowClear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  :label="t('activityManage.label.activityEndTime')"
                  v-bind="validateInfos.endTime"
                  name="endTime"
                >
                  <a-date-picker
                    style="width: 100%"
                    v-model:value="modelFrom.data.endTime"
                    :placeholder="t('placeholder.pleaseSelect')"
                    valueFormat="YYYY-MM-DD HH:mm:ss"
                    allowClear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item
                  :label="t('activityManage.label.activityIntroduction')"
                  :labelCol="{ span: 3 }"
                  v-bind="validateInfos.comment"
                  name="comment"
                >
                  <a-textarea
                    :auto-size="{ minRows: 2, maxRows: 6 }"
                    :maxlength="255"
                    v-model:value="modelFrom.data.comment"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item :label="t('activityManage.label.activityBudget')" name="buggetMoney">
                  <a-input
                    onkeyup="this.value=this.value.toString().match(/^\d{0,4}(?:\.\d{0,2})?/)"
                    v-model:value="modelFrom.data.buggetMoney"
                    :maxlength="18"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item :label="t('activityManage.label.personInCharge')" name="actHead">
                  <a-input v-model:value="modelFrom.data.actHead">
                    <template #addonAfter>
                      <div
                        class="primary-color cursor-pointer"
                        @click="openDialog('mainVisible')"
                      >
                        {{t('button.select')}}
                      </div>
                    </template>
                  </a-input>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item :label="t('activityManage.label.school')" name="school">
                  <a-input v-model:value="modelFrom.data.school">
                    <template #addonAfter>
                      <div
                        class="primary-color cursor-pointer"
                        @click="openDialog('schoolVisible')"
                      >
                        {{t('button.select')}}
                      </div>
                    </template>
                  </a-input>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item :label="t('activityManage.label.activityType')" name="actType">
                  <a-select
                    style="width: 100%"
                    :placeholder="t('placeholder.pleaseSelect')"
                    v-model:value="modelFrom.data.actType"
                    @change="handlePapers"
                  >
                    <a-select-option
                      v-for="item in dictLists.data[dictEnum.ACT_TYPE]"
                      :value="item.value"
                      :key="item.value"
                    >
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item :label="t('activityManage.label.estimatedContractAmount')" name="signMoney">
                  <a-input
                    onkeyup="this.value=this.value.toString().match(/^\d{0,4}(?:\.\d{0,2})?/)"
                    v-model:value="modelFrom.data.signMoney"
                    :suffix="t('placeholder.yuan')"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item :label="t('activityManage.label.saleHead')" name="actHead">
                  <a-input v-model:value="modelFrom.data.saleHead">
                    <template #addonAfter>
                      <div
                        class="primary-color cursor-pointer"
                        @click="openDialog('saleVisible', 'sale')"
                      >
                        {{t('button.select')}}
                      </div>
                    </template>
                  </a-input>
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item :label="t('activityManage.label.channel')" :labelCol="{ span: 3 }">
                  <div class="content-box">
                    <a-tag
                      v-for="(item, index) in formState.channels"
                      :key="index"
                      closable
                    >
                      {{ item }}
                    </a-tag>
                    <span
                      class="selects"
                      @click="handleSelect('channelVisible')"
                      >{{t('button.select')}}</span
                    >
                  </div>
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item
                  :label="t('activityManage.label.drainageDestination')"
                  :labelCol="{ span: 3 }"
                  name="ylBurn"
                >
                  <a-radio-group
                    name="radioGroup"
                    v-model:value="modelFrom.data.ylBurn"
                  >
                    <a-radio
                      v-for="(item, index) in plainOptions"
                      :key="index"
                      :value="item.value"
                    >
                      {{ item.label }}
                    </a-radio>
                  </a-radio-group>
                </a-form-item>
              </a-col>
              <a-col v-if="modelFrom.data.ylBurn == 1" :span="24">
                <a-form-item
                  class="form-label"
                  label=" "
                  :labelCol="{ span: 3 }"
                  :wrapperCol="{ span: 10 }"
                >
                  <a-radio v-model:value="modelFrom.data.isSetmoney">
                    {{ t('activityManage.label.whetherToSettleTheSalaryForTheCampusAmbassador') }}
                  </a-radio>
                </a-form-item>
              </a-col>
              <a-col v-else-if="modelFrom.data.ylBurn == 2" :span="24">
                <a-form-item
                  :label="t('activityManage.label.destination')"
                  :labelCol="{ span: 3 }"
                  :wrapperCol="{ span: 10 }"
                  name="ylBurn"
                >
                  <a-input v-model:value="modelFrom.data.webAdd" />
                </a-form-item>
              </a-col>
              <a-col v-else :span="24">
                <a-form-item :label="t('activityManage.label.sale')" :labelCol="{ span: 3 }" name="sale">
                  <div class="content-box">
                    <a-tag
                      v-for="(item, index) in formState.channelsSales"
                      :key="index"
                      closable
                    >
                      {{ item }}
                    </a-tag>
                    <span class="selects" @click="handleCheck('mainVisible')"
                      >{{t('button.select')}}</span
                    >
                  </div>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-card>
        <div class="pre-title">{{ t('activityManage.label.contractDetails') }}</div>
        <a-card>
          <a-form>
            <a-row v-for="(item, index) in contractDetail.data" :key="index">
              <a-col :span="18">
                <a-form-item :label="`${t('activityManage.label.requirement') + (index + 1)}`">
                  <a-input
                    v-model:value="item.signMoney"
                    :maxlength="100"
                    :placeholder="t('placeholder.pleaseEnter')"
                  ></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-button
                  style="margin-left: 20px"
                  @click="handleContract(index)"
                  :type="index == 0 ? 'primary' : 'danger'"
                  >{{ index == 0 ? t('button.save') : t('button.delete') }}</a-button
                >
              </a-col>
            </a-row>
          </a-form>
        </a-card>
        <div class="pre-title">{{ t('activityManage.label.attachmentInformation') }}</div>
        <a-card>
          <a-form>
            <a-row>
              <a-col :span="24">
                <a-form-item
                  :label="t('activityManage.label.contract')"
                  :labelCol="{ span: 3 }"
                  :wrapperCol="{ span: 10 }"
                >
                  <a-upload
                    name="files"
                    :file-list="fileProList"
                    :customRequest="handleProUpload"
                    @change="handleUploadProChange"
                  >
                    <a-button> <a-icon type="upload" />{{ t('button.upload') }}</a-button>
                  </a-upload>
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item
                  :label="t('channelManage.label.otherAccessories')"
                  :labelCol="{ span: 3 }"
                  :wrapperCol="{ span: 10 }"
                >
                  <a-upload
                    name="files"
                    :file-list="fileList"
                    :customRequest="handleUpload"
                    @change="handleUploadChange"
                  >
                    <a-button> <a-icon type="upload" />{{ t('button.upload') }}</a-button>
                  </a-upload>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-card>
      </a-col>
    </a-row>
    <school
      v-if="formState.schoolVisible"
      :visible="formState.schoolVisible"
      @selectUniversity="selectUniversity"
      @close="closeDialog"
    />
    <channel
      v-if="formState.channelVisible"
      :visible="formState.channelVisible"
      @checked="selectUniversity"
      @close="closeChannelDialog"
    />
    <channelSin
      :visible="formState.saleVisible"
      @selectUniversity="selectUniversity"
      @close="closeDialog"
    />
    <mainPerson
      v-if="formState.mainVisible"
      :visible="formState.mainVisible"
      :title="formState.mainTitle"
      :checkbox="formState.checkbox"
      @checked="selectUniversity"
      @close="closeChannelDialog"
    />
    <userTree
      :visible="formState.visibleUserTree"
      @close="closeGive"
      :record="formState.recordGive"
    ></userTree>
  </page-layout>
</template>

<script>
import school from "./modal/school.vue";
import channel from "./modal/channel.vue";
import userTree from "./modal/user-tree";
import mainPerson from "./modal/main-person";
import channelSin from "@/view/channel-manage/modal/channel.vue";
import {
  save,
  upload,
  update,
  details,
} from "@/api/module/activity-management";
import { getDictByCodesReturnObj } from "@/tools/get-dict";
import dictEnum from "@/const/dict";
import { onMounted, reactive, ref, toRaw, onActivated } from "vue";
import { Form, message } from "ant-design-vue";
import { useRouter, useRoute } from "vue-router";
import { useStore } from "vuex";
import moment from "moment";
import { useI18n } from "vue-i18n";

const useForm = Form.useForm;
export default {
  name: "activity-management-add",
  components: {
    school,
    userTree,
    channel,
    mainPerson,
    channelSin
  },
  setup() {
    const router = useRouter();
    const route = useRoute();
    const formRef = ref();
    const store = useStore();
    const { t } = useI18n();

    let dictLists = reactive({
      data: {},
    });
    let modelFrom = reactive({
      data: {
        ylBurn: "1",
      },
    });
    const contractDetail = reactive({
      data: [
        {
          id: "0",
          demand: "",
          tagPeople: store.state.user.userInfo.username || "",
        },
      ],
    });
    const formRules = {
      actName: [{ required: true, message: t('activityManage.label.active-name'), trigger: "blur" }],
      beginTime: [
        { required: true, type: 'date', message: t('activityManage.label.start-time'), trigger: "blur" },
      ],
      endTime: [{ required: true, type: 'date', message: t('activityManage.label.end-time'), trigger: "blur" }],
      comment: [{ required: true, message: t('activityManage.label.active-0'), trigger: "blur" }],
    };

    const { resetFields, validate, validateInfos } = useForm(
      modelFrom.data,
      formRules
    );
    const closeGive = function () {
      formState.visibleUserTree = false;
    };
    const fileList = ref();
    const fileProList = ref();
    // 上传文件
    const handleUpload = (data) => {
      const formData = new FormData();
      formData.append("file", data.file);
      upload(formData).then((res) => {
        if (res.code === 500) {
          message.error({ content: t('activityManage.label.active-1') });
          data.onError();
        } else {
          data.onSuccess(res.data);
        }
      });
    };
    // 附件
    const handleUploadChange = (info) => {
      let resFileList = [...info.fileList];
      resFileList = resFileList.slice(-1);
      resFileList = resFileList.map((file) => {
        if (file.response) {
          file.url = file.response.path;
          modelFrom.data.accessoryUrl = file.response.path;
        }
        return file;
      });
      fileList.value = resFileList;
    };
    // 上传文件
    const handleProUpload = (data) => {
      const formData = new FormData();
      formData.append("file", data.file);
      upload(formData).then((res) => {
        if (res.code === 500) {
          message.error({ content: t('activityManage.label.active-1') });
          data.onError();
        } else {
          data.onSuccess(res.data);
        }
      });
    };
    // 附件
    const handleUploadProChange = (info) => {
      let resFileList = [...info.fileList];
      resFileList = resFileList.slice(-1);
      resFileList = resFileList.map((file) => {
        if (file.response) {
          file.url = file.response.path;
          modelFrom.data.contractUrl = file.response.path;
        }
        return file;
      });
      fileProList.value = resFileList;
    };
    const formState = reactive({
      schoolVisible: false,
      channelVisible: false,
      visibleUserTree: false,
      mainVisible: false,
      saleVisible: false,
      recordGive: {},
      times: [],
      valueType: null,
      mainTitle: t('activityManage.label.active-2'),
      checkbox: false,
      buttons: [
        {
          name: "save",
          event: () => onSubmit(),
          type: "primary",
          code: "",
        },
        {
          name: "reset",
          event: () => resetForm(),
          code: "",
        },
      ],
      channels: [],
      channelsSales: [],
    });
    const labelCol = { span: 3, offset: 12 };
    const wrapperCol = { span: 14 };
    const resetForm = () => {
      formRef.value.resetFields()
      modelFrom.data = {}
      contractDetail.data = [
        {
          id: "0",
          demand: "",
          tagPeople: store.state.user.userInfo.username || "",
        },
      ]
    };

    const onSubmit = () => {
      formRef.value.validate().then(() => {
        const result = toRaw(modelFrom.data);
        result.contractDetail = JSON.stringify(contractDetail.data)
        if (result.id) {
          update(result)
            .then((res) => {
              if (res.success) {
                message
                  .success({ content: t('activityManage.label.active-2'), duration: 1 })
                  .then(() => {
                    router.push({
                      path: "/market/activity-management",
                    });
                    resetForm();
                  });
              } else {
                message.warning({ content: t('message.save-suc'), duration: 1 });
              }
            })
            .catch((err) => {
              console.log("err: ", err);
              message.warning({ content: t('message.save-fai'), duration: 1 });
            });
        } else {
          save(result)
            .then((res) => {
              if (res.success) {
                message
                  .success({ content: t('message.save-suc'), duration: 1 })
                  .then(() => {
                    router.push({
                      path: "/market/activity-management",
                    });
                    resetForm();
                  });
              } else {
                message.warning({ content: t('message.save-fai'), duration: 1 });
              }
            })
            .catch((err) => {
              message.warning({ content: t('message.save-fai'), duration: 1 });
            });
        }
      });
    };

    const openDialog = (value, type = null) => {
      formState.valueType = null
      if (type) {
        formState.valueType = type
      }
      formState[value] = true;
    };
    const handleChange = (value) => {
      console.log("value: handleChange", value);
    };

    const closeDialog = (type) => {
      if (formState.valueType == 'sale') {
        formState['saleVisible'] = false;
        return;
      }
      formState[type] = false;
    };
    const closeChannelDialog = (type) => {
      formState[type] = false;
    };

    const selectUniversity = (data) => {
      formState[data.visible] = false;
      if (data.visible == "channelVisible") {
        if (formState.valueType && formState.valueType == 'sale') {
          modelFrom.data.saleHead = data.data.nickname;
          modelFrom.data.saleHeadCode = data.data.id;
          formState['saleVisible'] = false;
        } else {
          const arr =
            data.data && Array.isArray(data.data)
              ? data.data.map((item) => item.chnName)
              : [];
          formState.channels = arr;
          modelFrom.data.channels = arr.join(",");
        }
      } else if (data.visible == "schoolVisible") {
        modelFrom.data.school = data.data.schoolEnName;
      } else {
        if (formState.checkbox) {
          const arr =
            data.data && Array.isArray(data.data)
              ? data.data.map((item) => item.nickname)
              : [];
          formState.channelsSales = arr;
          modelFrom.data.channelsSales = arr.join(",");
        } else {
          modelFrom.data.actHead = data.data.nickname;
        }
        formState.checkbox = false;
        formState.mainTitle = '';
      }
    };

    const handleContract = (idx) => {
      if (idx == 0) {
        contractDetail.data.push({
          id: "0",
          demand: "",
          tagPeople: store.state.user.userInfo.username || "",
        });
      } else {
        contractDetail.data = contractDetail.data.filter(
          (item, index) => index != idx
        );
      }
    };
    const handleSelect = (value) => {
      formState.valueType = null;
      if (value == "mainVisible") {
        formState.mainTitle = t('activityManage.label.active-2');
        formState.checkbox = false;
      }
      formState[value] = true;
    };
    const handleCheck = (value) => {
      if (value == "mainVisible") {
        formState.mainTitle = t('activityManage.label.active-3');
        formState.checkbox = true;
      }
      formState[value] = true;
    };
    const plainOptions = [
      { label: t('activityManage.label.active-4'), value: "1" },
      { label: t('activityManage.label.active-5'), value: "2" },
      { label: t('activityManage.label.active-6'), value: "3" },
    ];

    // 获取详情
    const getDetails = (id) => {
      if (!id) return;
      return details({ id }).then((res) => {
        if (res.success) {
          modelFrom.data = { ...res.data };
          contractDetail.data = JSON.parse(res.data.contractDetail)
        }
      });
    };
    const beginChange = (value) => {
      modelFrom.data.beginTime = moment(value._d).format('YYYY-MM-DD HH:mm:ss')
    }
    const endChange = (value) => {
      modelFrom.data.endTime = moment(value._d).format('YYYY-MM-DD HH:mm:ss')
    }
    onActivated(() => {
      const result = route.query;
      if (result && result.id) {
        getDetails(result.id);
      } else {
        resetForm();
      }
    });
    onMounted(async () => {
      dictLists.data = await getDictByCodesReturnObj([
        dictEnum.ACT_TYPE,
        dictEnum.ACT_STATUS,
      ]);
    });
    return {
      t,
      modelFrom,
      contractDetail,
      formRef,
      formRules,
      labelCol,
      fileList,
      fileProList,
      wrapperCol,
      openDialog,
      formState,
      handleChange,
      handleUpload,
      handleUploadChange,
      handleProUpload,
      handleUploadProChange,
      selectUniversity,
      closeDialog,
      plainOptions,
      handleSelect,
      resetFields,
      validateInfos,
      closeGive,
      dictEnum,
      dictLists,
      handleCheck,
      closeChannelDialog,
      handleContract,
      beginChange,
      endChange
    };
  },
};
</script>

<style lang="less" scoped>
.page-head {
  /deep/ .ant-page-header-heading-title {
    color: #2d8cf0;
  }
}

.pre-title {
  padding: 10px 25px;
  background-color: #f5f5f5;
  color: #555;
}

.content-box {
  position: relative;
  width: 100%;
  min-height: 50px;
  border: 1px solid #d9d9d9;
  background-color: #fff;
  background-image: none;
  border-radius: 2px;
  padding: 10px 40px 10px 10px;

  .selects {
    position: absolute;
    color: #2d8cf0;
    right: 5px;
    cursor: pointer;
    top: 50%;
    transform: translateY(-50%);
  }
}

.form-label {
  /deep/ .ant-form-item-label > label::after {
    content: "" !important;
  }
}
</style>